#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/9/4 10:47
# @Author  : 赵在化
# @email  : zaihuazhao@163.com
# @File    : loginout.py
from django.conf import settings
from django.contrib.auth import login, logout
from django.contrib.sessions.models import Session
from django.core.cache import cache

from lib.common import CacheKeys


def login_sys(request, user, is_elephant=0):
    """同账号只维护一个登录用户"""

    if not hasattr(user, 'backend'):
        user.backend = 'django.contrib.auth.backends.ModelBackend'

    login(request, user)
    if is_elephant:
        return

    key = CacheKeys.LOGIN_ID % user.id
    _session_key = request.session.session_key
    session = cache.get(key)
    if session:
        cache_key = session.get('cache_key')
        session_key = session.get('session_key')
        if not _session_key == session_key:  # 移动端重新登录会传上一次的sessionid
            cache.delete(cache_key)
            Session.objects.filter(session_key=session_key).delete()
        else:
            return
    _session = {}
    _session['session_key'] = request.session.session_key
    _session['cache_key'] = request.session.cache_key
    cache.set(key, _session, settings.SESSION_COOKIE_AGE)


def logout_sys(request, is_elephant=0):
    logout(request)
    if is_elephant:
        return

    cache.delete(CacheKeys.device_key.format(uid=request.user.id))
    cache.delete(CacheKeys.LOGIN_ID % request.user.id)


def logout_r(user_id):
    key = CacheKeys.LOGIN_ID % user_id
    session = cache.get(key)
    if session:
        cache_key = session.get('cache_key')
        session_key = session.get('session_key')
        cache.delete(cache_key)
        Session.objects.filter(session_key=session_key).delete()
